package com.xbx.admin.annotation.intercepter;

import com.google.gson.Gson;
import com.xbx.common.constant.GlobalConstant;
import com.xbx.baseweb.model.User;
import com.xbx.common.utils.DESEncryptUtils;
import com.xbx.admin.annotation.UserInfoContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

/**
 * 用户信息设置拦截器
 *
 * @author 89005691
 * @create 2018-10-08 15:00
 */
@Slf4j
public class TransmitUserInfoFeighClientIntercepter implements RequestInterceptor {

    @Value("${userInfoDesKey}")
    private String userInfoDesKey;

    public TransmitUserInfoFeighClientIntercepter() {
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //从应用上下文中取出user信息，放入Feign的请求头中
        User user = UserInfoContext.getUser();
        if (user != null) {
            try {

                String userJson = new Gson().toJson(user);
                requestTemplate.header(GlobalConstant.GLOBAL_USER_INFO, DESEncryptUtils.encrypt(userJson, userInfoDesKey));
            } catch (Exception e) {
                log.error("用户信息设置错误", e);
            }
        }
    }
}
